package com.firesrc.service.server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jodd.bean.BeanTool;
import jodd.datetime.JDateTime;
import jodd.typeconverter.Convert;
import jodd.util.PrettyStringBuilder;

import com.firesrc.bean.FullRecord;
import com.firesrc.bean.ProcessorBean;
import com.firesrc.bean.Record;
import com.firesrc.service.FullRecordService;
import com.firesrc.service.KeywordService;
import com.firesrc.service.impl.FullRecordServiceImpl;
import com.firesrc.service.impl.KeywordServiceImpl;
import com.firesrc.util.GenerateSequenceUtil;
import com.firesrc.util.SqlTsvTool;

public class ImportRecordCommand implements ProcessDataCommand {

  @Override
  public String process(ProcessorBean processorBean) {
    ResultSet rst = SqlTsvTool.getRstFromProcessorBean(processorBean);
    List<Record> importList = getRecordListFromRst(rst);
    FullRecordService service = new FullRecordServiceImpl();
    KeywordService keywordServie = new KeywordServiceImpl();
    FullRecord fullRecord = null;
    Set<String> keywordNameSet = new HashSet<String>();
    for (Record record : importList) {
      fullRecord = new FullRecord();
      BeanTool.copy(record, fullRecord);
      fullRecord.setId(GenerateSequenceUtil.generateSequenceNo());
      fullRecord.setSrcId(record.getId());
      service.add(fullRecord);
      keywordNameSet.add("'" + record.getKeyword() + "'");
    }
    PrettyStringBuilder psb = new PrettyStringBuilder();
    String string = psb.toString(keywordNameSet);
    keywordServie.setSearchedByNames(string);

    return string;
  }

  public List<Record> getRecordListFromRst(ResultSet rst) {
    List<Record> list = new ArrayList<Record>();
    Record record = null;
    try {
      while (rst.next()) {
        record = new Record();
        record.setId(rst.getString("ID"));
        record.setMail(rst.getString("MAIL"));
        record.setUrl(rst.getString("URL"));
        record.setKeyword(rst.getString("KEYWORD"));
        record.setContent(rst.getString("CONTENT"));
        record.setMailstate(rst.getString("MAILSTATE"));
        record.setTopic(rst.getString("TOPIC"));
        String date = rst.getString("SENDMAILDATE");
        if (date != null) {
          JDateTime jdata = new JDateTime(date);
          record.setSendmaildate(Convert.toDate(jdata));
        }
        list.add(record);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return list;
  }
}
